<?php

namespace App\Logic\Member\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberScoreModel;
use App\Model\Order\OrderModel;
use App\Model\UserModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\EasySwoole\Config as ESConfig;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;

class ScoreListForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $username;
    public $score;
    public $before_score;
    public $after_score;
    public $remark;
    public $type;
    public $object_id;
    public $referrer_profit_user_id;
    public $created_at;
    public $start_created_at;
    public $end_created_at;
    public $group;
    public $date;


    /**
     * 账户积分变动列表
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function lists()
    {
        $where = [];
        $table_date = '';//月份分表
        if(UserIdentityHelper::getType() == UserModel::TYPE_INSIDE) {
            /**后台管理员*/
            if ($this->checkField($this->user_id)) {
                $where['user_id'] = $this->user_id;
            }
            if ($this->checkField($this->username)) {
                if(!$member = MemberModel::create()->getOne(['username' => $this->username])){
                    throw new DefaultException('用户不存在');
                }
                $where['user_id'] = $member->id;
            }
        }else{
            $this->user_id = UserIdentityHelper::getId();
            $where['user_id'] = $this->user_id;
        }

        if ($this->checkField($this->id)) {
            $where['id'] = $this->id;
        }
        if ($this->checkField($this->type)) {
            $where['type'] = $this->type;
        }
        if ($this->checkField($this->referrer_profit_user_id)) {
            $subBuilder = QueryBuilder::subQuery();
            $subBuilder->where('user_id', $this->referrer_profit_user_id);
            $subBuilder->get(OrderModel::create()->tableName(), null, "id");
            $where['object_id'] = [$subBuilder, 'in'];
            $where['type'] = MemberScoreModel::TYPE_REFFERER_PROFIT;
        }
        if (!is_array($this->created_at) && $this->checkField($this->created_at) && strtotime($this->created_at) > 0) {
            $this->created_at = date('Y-m-d', strtotime($this->created_at));
            $where['created_at'] = [[$this->created_at . ' 00:00:00', $this->created_at . ' 23:59:59'], 'between'];
            $table_date = date('Ym', strtotime($this->created_at));
        }
        if ($this->checkField($this->date) && strtotime($this->date) > 0) {
            $firstDay = date('Y-m-01', strtotime($this->date)) . ' 00:00:00';
            $lastDay = date('Y-m-t', strtotime($this->date)). ' 23:59:59';
            $where['created_at'] = [[$firstDay, $lastDay ], 'between'];
            $table_date = date('Ym', strtotime($this->date));
        }
        if ($this->checkField($this->start_created_at) && $this->checkField($this->end_created_at)) {
            /**查询时间不能跨月*/
            $start_month = date('Y-m', strtotime($this->start_created_at));
            $end_month = date('Y-m', strtotime($this->end_created_at));
            if($start_month != $end_month) {
                throw new DefaultException('查询时间不能跨月');
            }
            $where['created_at'] = [[$this->start_created_at, $this->end_created_at], 'between'];
            $table_date = date('Ym', strtotime($this->start_created_at));
        }elseif ($this->checkField($this->start_created_at)) {
            $where['created_at'] = [$this->start_created_at, '>='];
            $table_date = date('Ym', strtotime($this->start_created_at));
        }elseif ($this->checkField($this->end_created_at)) {
            $where['created_at'] = [$this->end_created_at, '<='];
            $table_date = date('Ym', strtotime($this->end_created_at));
        }
        $model = MemberScoreModel::makeQueryModel($where, [], $this->getPagination());//->setTableNameByMonth($table_date);
        $model = CommonHelper::setTableNameByMonth($model, $table_date);
//        if($table_date){
//            /**如果不是当前月,那么就去取分表数据*/
//            $now_month = date('Ym');
//            if($table_date < $now_month){
//                /**判断当前月份分表是否存在*/
//                $database_name = ESConfig::getInstance()->getConf('MYSQL_READ')['database'];
//                $table_date_table_name = MemberScoreModel::create()->getTableName() . '_' . $table_date;
//                $sql = <<<sql
//
//                    SELECT COUNT(*) `cnt`
//                    FROM information_schema.tables
//                    WHERE table_schema = '{$database_name}'
//                    AND table_name = '{$table_date_table_name}'
//sql;
//                $queryBuild = new QueryBuilder();
//                $queryBuild->raw($sql);
//                $result = DbManager::getInstance()->query($queryBuild, true, 'write');
//                if($result->getResult()[0]['cnt'] == 1) {
//                    $model->tableName(MemberScoreModel::create()->getTableName() . '_' . $table_date,  true);
//                }
//            }
//        }

        $model->with(['member']);
        $model->order( 'id', 'DESC');

        $modelResult = $model->all();

        $list = [];
        foreach($modelResult as $v) {
            $item = [
                'id'                 => $v->id,
                'user_id'            => $v->user_id,
                'username'          => $v->member->username ?? '',
                'score'              => $v->score,
                'before_score'       => $v->before_score,
                'after_score'        => $v->after_score,
                'type'               => $v->type,
                'object_id'          => $v->object_id,
                'created_at'         => $v->created_at,
                'type_label'         => MemberScoreModel::getTypeDict($v->type),
                'remark'             => $v->remark,
            ];
            $list[] = $item;
        }
        /**筛选出所有type=TYPE_REFFERER_PROFIT 的项目,取出object_id*/
        $reffererProfitList = array_filter($list, function($item) {
            return $item['type'] == MemberScoreModel::TYPE_REFFERER_PROFIT;
        });
        $reffererProfitObjectIdList = array_column($reffererProfitList, 'object_id');
        /**用$reffererProfitObjectIdList 中订单号3-8位分组 获取订单号中包含了年月信息*/
        $orderMonths = [];
        $reffererProfitObjectIdList = array_filter($reffererProfitObjectIdList, function($item) use(&$orderMonths) {
            $month = substr($item, 2, 6);
            $orderMonths[$month] = $month;
            return true;
        });
        /**如果$reffererProfitObjectIdList不为空,那么就通过id去获取订单信息*/
        if(!empty($reffererProfitObjectIdList)) {
            $reffererProfitObjectIdList = array_unique($reffererProfitObjectIdList);

            foreach ($orderMonths as $month) {
                /**当前月就查询ss_order_returned,否则查询月份分表*/
                if ($month == date('Ym')) {
                    $table_order = 'returned';
                } else {
                    $table_order = $month;
                }
                /**@see OrderModel::member() */
                $orderModel = OrderModel::makeQueryModel(['id' => [$reffererProfitObjectIdList, 'IN']]);
                $orderModel = $orderModel->tableName($orderModel::create()->getTableName() . '_' . $table_order);
                if ($reffererProfitOrders = $orderModel->with(['member'])->all()) {
                    $orders = [];
                    foreach ($reffererProfitOrders as $order) {
                        $item             = $order->toRawArray();
                        $item['username'] = $order->member->username;
                        $orders[]         = $item;
                    }

                    /**轮询reffererProfitOrders=>$order,如果$list中的object_id等于order中的id,那么将order.user_id赋值给$item['order_user_id']*/
                    $list = array_map(function ($item) use ($orders) {
                        $order = array_filter($orders, function ($order) use ($item) {
                            return $order['id'] == $item['object_id'];
                        });
                        if (!empty($order)) {
                            $order                  = array_shift($order);
                            $item['order_user_id']  = $order['user_id'];
                            $item['order_username'] = $order['username'];
                            $item['order_id']       = $order['id'];
                        }
                        return $item;
                    }, $list);
                }
            }
        }

        if(!empty($this->group)) {
            $summarizedData = [];
            foreach ($list as $item) {
                $date                                 = date('Y-m-d', strtotime($item['created_at'])); // 提取日期部分
                $day                                  = date('Y年m月d日', strtotime($date)); // 格式化日期
                $summarizedData[$date]['item'][]      = $item;
                $summarizedData[$date]['day']         = $day;
                $summarizedData[$date]['total_score'] = isset($summarizedData[$date]['total_score']) ? bcadd($summarizedData[$date]['total_score'], $item['score'], 2) : $item['score'];
            }

            $list = array_values($summarizedData);
        }
        $total = $model->lastQueryResult()->getTotalCount();
        $pagination = $this->getPagination();
        $pagination['total_count'] = $total;

        $result = [
            'list'       => $list,
            'pagination' => $pagination
        ];
        return $result;
    }

}
